package com.starblink.brand.search.ui

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxItemDecoration
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.annotaion.DividerOrientation
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.grid
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.widget.ConfirmDialog2
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.KeyboardUtils
import com.starblink.brand.BrandHelper
import com.starblink.brand.databinding.ActivityBrandSearchBinding
import com.starblink.brand.databinding.CellBrandSearchEmptyBinding
import com.starblink.brand.databinding.CellBrandSearchRecommendTitleBinding
import com.starblink.brand.databinding.CellSimpleProductCardBrandBinding
import com.starblink.brand.search.bean.RvNoDataEntry
import com.starblink.brand.search.bean.RvProductWapper
import com.starblink.brand.search.bean.RvRecommendTitleEntry
import com.starblink.brand.widget.BrandChangeViewDialog
import com.starblink.library.widget.holder.HistoryAdapter
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.library.widget.sort.SortUtils

/**品牌奥莱搜索页*/
@Route(path = RoutePage.Brand.BRAND_SEARCH)
class BrandSearchActivity : BaseTVMActivity<ActivityBrandSearchBinding, BrandSearchVM>() {
    override fun initViewBinding(): ActivityBrandSearchBinding =
        ActivityBrandSearchBinding.inflate(layoutInflater)

    @Autowired(name = RoutePage.Brand.ARG_BRAND_ID)
    @JvmField
    var brandId: String? = ""

    @Autowired(name = RoutePage.Brand.ARG_BRAND_NAME)
    @JvmField
    var brandName: String? = ""

    @Autowired(name = RoutePage.Brand.ARG_IS_DISCOUNT_BRAND)
    @JvmField
    var isDiscountBrand: Boolean = false

    private val historySearchWordsAdapter by lazyOnNone {
        HistoryAdapter(
            viewBinding.layoutSearchHistory.rvHistory,
            viewModel.historySearchWords
        ) {
            // 点击历史搜索词，开始搜索
            viewBinding.layoutTopBar.etSearchInput.setText(it)
            viewBinding.layoutTopBar.etSearchInput.setSelection(it.length)
            doSearchAction(it)

            // 埋点:品牌二级页-搜索容器页-历史搜索-点击
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        SpmPageDef.BrandSearchDefaultPage,
                        SpmElementDef.SearchHistoryItemClick
                    ),
                    params = mapOf(
                        "brandName" to (viewModel.brandName),
                        "searchTerm" to it
                    )
                )
            )
        }
    }

    // 店铺搜索结果列表Adapter
    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.searchProducts).apply {
            addVhDelegate {
                SearchEmptyCell(
                    CellBrandSearchEmptyBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                RecommendTitleCell(
                    CellBrandSearchRecommendTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                ProductCardCell(
                    activity = this@BrandSearchActivity,
                    binding = CellSimpleProductCardBrandBinding.inflate(
                        it.inflater,
                        it,
                        false
                    ),
                    brandName = viewModel.brandName,
                    searchProducts = viewModel.searchProducts,
                    searchKeyword = viewModel.searchKeyword,
                )
            }
        }
    }

    override fun initData() {
        super.initData()
        viewModel.brandId = brandId ?: ""
        viewModel.brandName = brandName ?: ""
        viewModel.isDiscountBrand = isDiscountBrand
    }

    override fun initView() {
        super.initView()

        initViewTopBar()
        initViewSearchHistory()
        initViewSort()
        initViewRvProducts()
    }

    private fun initViewTopBar() {
        viewBinding.layoutTopBar.etSearchInput.hint = " Search in ${brandName}"
        viewBinding.layoutTopBar.etSearchInput.requestFocus()
        viewBinding.layoutTopBar.etSearchInput.setOnEditorActionListener { _, actionId, _ ->
            if (EditorInfo.IME_ACTION_SEARCH == actionId) {
                doSearchAction(viewBinding.layoutTopBar.etSearchInput.text.trim())
                true
            } else {
                false
            }
        }
        viewBinding.layoutTopBar.etSearchInput.addTextChangedListener {
            viewBinding.layoutTopBar.btnClear.visibleOrGone(it.toString().isNotEmpty())
        }
        viewBinding.layoutTopBar.btnClear.click {
            // 点击清除按钮，如果正在初始搜索页面，不用做任何操作；如果正在显示搜索结果，返回到初始搜索页面
            viewBinding.layoutTopBar.etSearchInput.setText("")
            if (viewBinding.page.visibility == View.VISIBLE) {
                // 隐藏搜索结果视图
                viewBinding.layoutSort.root.gone()
                viewBinding.page.gone()
                viewModel.searchProducts.clear()
                adapter.notifyDataSetChanged()

                viewModel.loadHistorySearchWords() // 重新加载搜索词
            }
        }
    }

    private fun initViewSearchHistory() {
        viewBinding.layoutSearchHistory.btnDelete.setOnClickListener {
            ConfirmDialog2.Builder(this)
                .setCancelButton(R.string.cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .setSureButton(R.string.confirm) { dialog, _ ->
                    viewModel.clearHistorySearchWords()
                    dialog.dismiss()
                }
                .setTitle("Clear Search History?")
                .create().show()
        }

        viewBinding.layoutSearchHistory.rvHistory.layoutManager = FlexboxLayoutManager(this).apply {
            flexDirection = FlexDirection.ROW
            justifyContent = JustifyContent.FLEX_START
            maxLine = 10
            flexWrap = FlexWrap.WRAP
        }
        viewBinding.layoutSearchHistory.rvHistory.addItemDecoration(FlexboxItemDecoration(this).apply {
            setDrawable(object : ColorDrawable(Color.TRANSPARENT) {
                override fun getIntrinsicWidth(): Int = 10.dp2px()
                override fun getIntrinsicHeight(): Int = 10.dp2px()
            })
        })
        viewBinding.layoutSearchHistory.rvHistory.adapter = historySearchWordsAdapter

        viewModel.historySearchWordsLD.observe(this) {
            if (it == true) {
                // 有搜索词
                viewBinding.layoutSearchHistory.root.visible()
                viewBinding.layoutSearchHistoryEmpty.root.gone()
                historySearchWordsAdapter.notifyItemRangeChanged(
                    0,
                    historySearchWordsAdapter.itemCount
                )
            } else {
                // 无搜索词，显示空视图
                viewBinding.layoutSearchHistory.root.gone()
                viewBinding.layoutSearchHistoryEmpty.root.visible()
            }
        }
    }

    private fun initViewSort() {
        viewBinding.layoutSort.vSortPrice.setOnClickListener {
            if (viewModel.sortType == SortTypeEnum.PRICE_L2H) {
                // 第二次点击Price，显示H2L
                viewModel.sortType = SortTypeEnum.PRICE_H2L
                viewBinding.layoutSort.vSortPrice.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_h2l1)
            } else if (viewModel.sortType == SortTypeEnum.PRICE_H2L) {
                // 第三次点击Price，显示默认
                viewModel.sortType = SortTypeEnum.DEFAULT
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
            } else {
                // 第一次点击Price，显示L2H

                // 取消Discount排序
                if (viewModel.sortType != SortTypeEnum.DEFAULT) {
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, false)
                }

                viewModel.sortType = SortTypeEnum.PRICE_L2H
                SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, true)
                viewBinding.layoutSort.vSortPrice.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_l2h1)
            }
            // 重新加载数据
            viewModel.searchProducts(refresh = true)
        }

        viewBinding.layoutSort.vSortDiscount.visibleOrGone(isDiscountBrand) {
            setOnClickListener {
                if (viewModel.sortType == SortTypeEnum.DISCOUNT_H2L) {
                    // 第二次点击Discount，显示L2H
                    viewModel.sortType = SortTypeEnum.DISCOUNT_L2H
                    viewBinding.layoutSort.vSortDiscount.icon =
                        CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_l2h1)
                } else if (viewModel.sortType == SortTypeEnum.DISCOUNT_L2H) {
                    // 第三次点击Discount，显示默认
                    viewModel.sortType = SortTypeEnum.DEFAULT
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, false)
                } else {
                    // 第一次点击Discount，显示H2L

                    // 取消Price排序
                    if (viewModel.sortType != SortTypeEnum.DEFAULT) {
                        SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
                    }

                    viewModel.sortType = SortTypeEnum.DISCOUNT_H2L
                    SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, true)
                    viewBinding.layoutSort.vSortDiscount.icon =
                        CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_sort_discount_h2l1)
                }
                // 重新加载数据
                viewModel.searchProducts(refresh = true)
            }
        }

        viewBinding.layoutSort.vSwitchView.setImageResource(if (BrandHelper.showSimpleViewInBrandSearch) com.starblink.brand.R.drawable.ic_brand_change_view_simple else com.starblink.brand.R.drawable.ic_brand_change_view_origin)
        viewBinding.layoutSort.vSwitchView.click {
            val dialog =
                navigationTo(RoutePage.Brand.DIALOG_CHANGE_VIEW) {
                    withBoolean(
                        RoutePage.Brand.ARG_SIMPLE_VIEW,
                        BrandHelper.showSimpleViewInBrandSearch
                    )
                } as BrandChangeViewDialog
            dialog.show(supportFragmentManager, "BrandChangeViewDialog")
        }
        supportFragmentManager.setFragmentResultListener(
            BrandChangeViewDialog.RESULT_SIMPLE_VIEW,
            this
        ) { _, bundle ->
            val res = bundle.getBoolean(BrandChangeViewDialog.ARG_RESULT, false)
            if (res != BrandHelper.showSimpleViewInBrandSearch) {
                // 修改了视图模式，更新数据
                BrandHelper.showSimpleViewInBrandSearch = res
                viewBinding.layoutSort.vSwitchView.setImageResource(if (BrandHelper.showSimpleViewInBrandSearch) com.starblink.brand.R.drawable.ic_brand_change_view_simple else com.starblink.brand.R.drawable.ic_brand_change_view_origin)
                viewModel.searchProducts.forEach {
                    if (it is RvProductWapper) {
                        it.showSimpleView = BrandHelper.showSimpleViewInBrandSearch
                    }
                }
                adapter.notifyDataSetChanged()
            }
        }
    }

    /**
     * 显示初始状态的排序视图
     */
    private fun showInitStateSortView() {
        viewBinding.layoutSort.root.visible()

        // 默认排序
        viewModel.sortType = SortTypeEnum.DEFAULT
        // 设置排序按钮未选中
        SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortPrice, false)
        SortUtils.setSortViewSelected(viewBinding.layoutSort.vSortDiscount, false)
    }

    private fun initViewRvProducts() {
        viewBinding.rv.grid(2).divider {
            setDivider(9, true)
            orientation = DividerOrientation.VERTICAL
        }
        (viewBinding.rv.layoutManager as GridLayoutManager).spanSizeLookup =
            object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    val item = try {
                        adapter.list[position]
                    } catch (e: Exception) {
                        null
                    }
                    return when (item) {
                        is RvNoDataEntry -> 2
                        is RvRecommendTitleEntry -> 2
                        else -> 1
                    }
                }
            }

        viewBinding.page.onRefresh {
            // 错误重试
            viewModel.searchProducts(refresh = true, isShowInitStateSortView = true)
        }

        viewBinding.page.onLoadMore {
            if (viewModel.searchResultEmpty) {
                viewModel.loadRecommendProducts(refresh = false)
            } else {
                viewModel.searchProducts(refresh = false)
            }
        }

        viewModel.searchResultLD.observe(this) {
            if (it.isRefresh) {
                if (it.isShowInitStateSortView) {
                    // 仅当搜索新文本，并成功返回搜索结果时，显示初始状态排序视图
                    showInitStateSortView()
                } else if (viewModel.searchResultEmpty) {
                    // 搜索结果为空，显示空视图时，隐藏排序视图
                    viewBinding.layoutSort.root.gone()
                }
            }

            // 显示列表数据
            if (viewBinding.rv.adapter == null) {
                // 当显示搜索结果首页数据时 或 搜索结果为空显示空视图+推荐商品列表首页时，执行此处逻辑
                viewBinding.rv.adapter = adapter
            } else {
                adapter.notifyDataSetChanged()
            }
            viewBinding.page.showContent()
            LoadingDialogManager.get().dismissLoading()
        }

        viewModel.mLoadActionLiveData.observe(this) {
            LoadingDialogManager.get().dismissLoading()
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError(it.errorCode)
                }

                LoadAction.STATE_NO_DATA -> {
                    viewBinding.page.finishLoadMoreWithNoMoreData()
                }
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        // 打开页面，默认加载显示历史搜索词
        viewModel.loadHistorySearchWords()
        // 自动显示软键盘
        viewBinding.root.postDelayed({
            KeyboardUtils.showSoftkeyboard(this)
        }, 200)
    }

    /**
     * 执行搜索动作
     */
    private fun doSearchAction(searchContent: CharSequence?) {
        if (searchContent.isNullOrEmpty()) return
        val keyword = searchContent.toString()
        viewModel.searchKeyword = keyword
        viewModel.sortType = SortTypeEnum.DEFAULT
        viewModel.saveToHistorySearchWords(keyword)

        // 隐藏搜索历史，显示LoadingView
        viewBinding.layoutSearchHistory.root.gone()
        viewBinding.layoutSearchHistoryEmpty.root.gone()
        viewBinding.page.visible()
        // 埋点：搜索结果页曝光
        pageExposure(
            SpmPageDef.BrandSearchPage,
            params = mapOf(
                "brandName" to (brandName ?: ""),
                "searchTerm" to viewModel.searchKeyword,
                "searchType" to "normal",
            )
        )

        viewModel.searchProducts(refresh = true, isShowInitStateSortView = true)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.BrandSearchPage)
    }
}